package com.cy.pj.module.controller;

import com.cy.pj.module.pojo.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
//22222  只展现json字符串

//@Controller
//@ResponseBody
@RestController   //@Controller+@ResponseBody
public class JsonController {
    @RequestMapping("/doGetResponse")
    public ResponseResult doHandleRequest() {
        ResponseResult rs = new ResponseResult();
        rs.setCode(200);
        rs.setMessage("ok");
        return rs;
    }


    //@RequestMapping("/health.html")名字随便取
    @RequestMapping("/doGetHealthJSON")
    //@ResponseBody
    //此注解描述控制层方法时，用来告诉spring框架，这个方法返回值尽量转换为json字符串响应到客户端
    //将转换以后的结果写到response对象的响应体中
    //方法的返回值不再封装到ModelAndView对象，不会再交给解析器解析，而是直接基于response对象响应到客户端
    public Map<String, Object> doHealth() {
        Map<String, Object> map = new HashMap<>();
        map.put("username", "刘德华");
        map.put("state", true);
        return map;
    }


    @RequestMapping("/doPrint")
    //@ResponseBody
    public void doPrint(HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("username", "刘德华");
        map.put("state", true);
        //将map中的数据转换成json格式字符串
        ObjectMapper om = new ObjectMapper();
        String jsonstr = om.writeValueAsString(map);
        System.out.println("jsonstr" + jsonstr);
        //将字符串响应到客户端
        //设置响应数据的编码
        response.setCharacterEncoding("utf-8");
        //告诉客户端要向它响应的数据类型为text/html，编码为utf-8,请以这种编码进行数据呈现
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.print(jsonstr);

    }
}
